package com.jiuhaohealth.common.util;

import java.util.ArrayList;

import net.sf.ezmorph.object.DateMorpher;
import net.sf.json.JSONObject;
import net.sf.json.util.JSONUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jiuhaohealth.common.page.PageModel;


public class MessageUtil {

	protected final static Logger logger = LoggerFactory.getLogger(MessageUtil.class);
	
	private static final String state = "state";
	private static final int stateSuc = 0;
	private static final String message = "message";
	private static final String content = "content";
	
	private static final String offset = "offset";
	private static final String ps = "ps";
	private static final String totalNumber = "totalNumber";
	private static final String data = "data";
	
	/**
	 * 按约定格式从json转成page对象
	 * */
	public static <T> PageModel<T> getPageModel(String json, Class<T> clazz) {
		String[] dateFormats = new String[] {"yyyy-MM-dd HH:mm:ss"};   
		JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(dateFormats));  
		JSONObject jo = JSONObject.fromObject(json);
		PageModel<T> model = new PageModel<T>();
		if(jo.getInt(state) == (stateSuc)) {
			JSONObject jcontent = jo.getJSONObject(content);
			if(jcontent.containsKey(offset))
				model.setOffset(jcontent.getInt(offset));
			if(jcontent.containsKey(ps))
				model.setPageSize(jcontent.getInt(ps));
			if(jcontent.containsKey(totalNumber))
				model.setTotalNumber(jcontent.getInt(totalNumber));
			if(jcontent.containsKey(data))
				model.setData(JsonUtil.jsonArrayToList(jcontent.getString(data), clazz));
 		}
		if(model.getData() == null)
			model.setData(new ArrayList<T>(0));		//为空返回空对象
		return model;
	}	
}
